package com.demo.task.ext

import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.provider.Settings
import com.demo.task.MainApplication
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader

fun Context.defaultLaunch() {
    "pm set-home-activity $packageName/$packageName.ui.MainActivity".runCommand()
}

fun Context.chmodExternalFiles() {
    "chmod 777 -R ${getExternalFilesDir()}".runCommand()
}

fun Context.clearData() {
    "pm clear $packageName".runCommand()
}

fun getSerial(): String {
    return try {
        // 执行 shell 命令获取序列号
        val process = Runtime.getRuntime().exec("getprop ro.serialno")
        BufferedReader(InputStreamReader(process.inputStream)).use {
            it.readLine()
        }
    } catch (e: Exception) {
        e.printStackTrace()
        ""
    }
}

fun getVersion(): String {
    return try {
        val manager: PackageManager = MainApplication.instance.packageManager
        val info: PackageInfo = manager.getPackageInfo(MainApplication.instance.packageName, 0)
        info.versionName.orEmpty()
    } catch (e: Exception) {
        e.printStackTrace()
        ""
    }
}

fun getScreenSize(): Pair<Int, Int> {
    val pair = Pair(0, 0)
    return try {
        val process = Runtime.getRuntime().exec("wm size")
        BufferedReader(InputStreamReader(process.inputStream)).use { bufferedReader ->
            val readLine = bufferedReader.readLine()
            process.waitFor()

            val dimensions = readLine?.substringAfter(": ")
                ?.split("x")
                ?: return pair
            val width = dimensions[0].trim().toInt()
            val height = dimensions[1].trim().toInt()
            Pair(width, height)
        }
    } catch (e: Exception) {
        pair
    }
}

fun Context.setAirPlaneMode(enable: Boolean) {
    Settings.Global.putInt(
        contentResolver,
        Settings.Global.AIRPLANE_MODE_ON,
        if (enable) 1 else 0
    )
    val intent = Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED)
    intent.putExtra("state", enable)
    sendBroadcast(intent)
}

fun screenshot(): File {
    val currentTime = currentTime().filter { it.isDigit() }
    val savePath = getExternalFilesDir("screenshot")
    val photoName = "${getSerial()}_$currentTime.png"
    val command = "screencap -p $savePath/$photoName"
    command.runCommand()
    return File(savePath, photoName)
}

fun getMemoryInfo(): Map<String, String> {
    val command = "cat /proc/meminfo"
    val runCommandAsResult = command.runCommandAsResult()
    return calculateMemoryInfo(runCommandAsResult)
}

fun getStorageInfo(): Map<String, String> {
    val command = "df -h"
    val runCommandAsResult = command.runCommandAsResult()
    return calculateTotalStorage(runCommandAsResult)
}

private fun calculateMemoryInfo(dfOutput: String): Map<String, String> {
    val lines = dfOutput.trim().split("\n")
    if (lines.size < 2) return mapOf()

    val params = mutableMapOf<String, String>()
    // 遍历每一行（跳过表头）
    for (element in lines) {
        val line = element.trim()
        val parts = line.split("\\s+".toRegex())
        if (parts.size < 3) continue
        when {
            line.contains("MemTotal:") -> {
                params["ram"] = parts[1]
            }

            line.contains("MemAvailable:") -> {
                params["ramu"] = parts[1]
            }

            else -> {}
        }
    }

    // 构建 JSON
    return params
}

private fun calculateTotalStorage(dfOutput: String): Map<String, String> {
    val lines = dfOutput.trim().split("\n")
    if (lines.size < 2) return mapOf()

    // 遍历每一行（跳过表头）
    for (i in 1 until lines.size) {
        val line = lines[i].trim()
        if (line.contains("/storage/emulated")) {
            val parts = line.split("\\s+".toRegex())
            if (parts.size < 5) continue
            // 提取 Size, Used, Avail
            val sizeStr = parts[1]
            val usedStr = parts[2]
            val availStr = parts[3]

            // 构建 JSON
            return mapOf(
                "disk" to sizeStr,
                "disku" to usedStr,
            )
        }
    }

    // 构建 JSON
    return mapOf()
}